<?php
/**
 * 东方联信 语音通知
 */
namespace app\common\model;
use think\Model;
use think\Db;
use think\cache\driver\Redis;

class VoiceNotice extends Model
{   
    const VOICE_START_TIME  = '10:00:00'; // 语音电话起始时间
    const VOICE_END_TIME    = '18:00:00'; // 语音电话终止时间
    const VOICE_REPLAY_TIME = '7200';     // 失败重拨时间间隔 单位秒 

    protected $name = 'voice';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $autoWriteTimestamp = 'datetime';

    /**
     * 发起语音电话请求并创建语音表
     * @author yhq <934797303@qq.com>
     * @date   2018-04-04
     * @param  [string]     $uid     [用户id]
     * @param  [string]     $phone   [手机号]
     * @param  [string]     $voiceTemplateId [语音模板号]
     * @param  [int]        $call_reason_type [拨打语音的原因目的]
     * @return [boolean]              
     */
    public function createVoice($uid, $phone, $voiceTemplateId, $call_reason_type='')
    {
        $now = time();
        if ($now < strtotime(self::VOICE_START_TIME) || $now > strtotime(self::VOICE_END_TIME)) {
            $this->error = '当前时间不能拨打语音电话';
            return false;
        }

        $lastTime = $this->where('phone', $phone)->order('id desc')->value('create_time');
        if(!empty($lastTime) && $now - strtotime($lastTime) < self::VOICE_REPLAY_TIME){
            $this->error = '两次语音时间间隔不足'.self::VOICE_REPLAY_TIME.'秒';
            return false;
        }

        switch ($call_reason_type) {
            case 0:
                $call_reason = '明天到期';
                break;
            case 1:
                $call_reason = '今天到期';
                break;
            case 2:
                $call_reason = '今天逾期';
                break;
            default:
                $call_reason = '未定义';
                break;
        }
        
        $sendVoiceNotice = $this->sendVoiceNotice($phone, $voiceTemplateId);
        if($sendVoiceNotice){
            $data = [
                'uid'              => $uid,
                'phone'            => $phone,
                'taskId'           => $sendVoiceNotice['taskId'],
                'voiceTemplateId'  => $voiceTemplateId,
                'call_reason_type' => $call_reason_type,
                'call_reason'      => $call_reason
            ];

            $add = $this->allowField(true)->create($data);
            return true;
        }

        return false;
    }

    /**
     * 更新语音信息
     * @author yhq <934797303@qq.com>
     * @date   2018-04-04
     * @param  [array]     $notifyResp [回调参数]
     * @return [boolean]
     */
    public function updateVoice($notifyResp)
    {
        #### 入参示例 ####       
        // array(10) {
        //       ["taskId"] => string(18) "201804121475542067"  // 接入方通过语音通话绑 定接口提交的请求 ID
        //       ["billId"] => string(36) "26e1112c-2b17-4291-a751-6bbc4714ac90" //绑定关系 ID
        //       ["caller"] => string(11) "07902104294" // 主叫号码
        //       ["callee"] => string(11) "13620977292" // 被叫号码
        //       ["duration"] => string(1) "9"          // 通话时长
        //       ["hangupReason"] => string(2) "16" 挂断原因(见附一)
        //       ["billType"] => string(1) "2"                           //  (这是一个未知参数)
        //       ["startTime"] => string(19) "2018-04-12 17:13:27"       // 开始时间，格式为： yyyy-MM-ddHH:mm:ss
        //       ["endTime"] => string(19) "2018-04-12 17:13:36"         // 结束时间，格式为： yyyy-MM-ddHH:mm:ss
        //       ["result"] => string(72) "债务人电话13620977292[正常拨打]并且已接听,通话时长9秒" //文本结果
        // }

        if($this->where('taskId', $notifyResp['taskId'])->count() < 0){
            $this->error = '不存在此数据';
            return false;   
        }

        // $code = [
        //     '0'  => '未规定',
        //     '16' => '正常挂断',
        //     '17' => '用户忙',
        //     '18' => '无用户响应',
        //     '19' => '无用户应答',
        //     '20' => '用户缺席',
        //     '21' => '呼叫拒绝',
        //     '22' => '号码变更',
        //     '28' => '无效的号码格式',
        //     '34' => '无可用电路',
        //     '38' => '网络失序',
        //     '41' => '临时故障',
        // ];
        // $notifyResp['hangupReason'] = $code[$notifyResp['hangupReason']];
        $notifyResp['hangupReason'] = $notifyResp['call_result'];

        $update = $this->allowField(true)->save($notifyResp, ['taskId'=>$notifyResp['taskId']]);
        if(!$update){
            $this->error = '更新失败';
            return false;     
        }

        return true;
    }


    /**
     * 发送语音通知接口
     * @param  [string]   $phone    [手机号]
     * @param  [string]   $voiceTemplateId  [语音模板号]
     * @return [boolean]            [成功或者失败]
     */
    public  function sendVoiceNotice($phone, $voiceTemplateId)
    {
        $channel     = config('operator_channel');
        $notifyUrl   = config('domainPath')['api'].'/v2/voiceNotify';
        $postUrl     = 'http://api.qhweidai.com/api/new_notice';
        $channelname = config('SYSTEM_NAME');

        $param = [
            'called'          => $phone,             //手机号
            'varContent'      => $channelname,       //此字段提供文本内容 模板中@占位符对应的具体内容
            'notifyUrl'       => $notifyUrl,         //话单异步接受地址
            'voiceTemplateId' => $voiceTemplateId,   //模板ID 可线上配置
            'channel'         => $channel            //渠道号 (必填)
        ];

        try {
            $res = curlPost($postUrl, $param);

            $res = json_decode($res, true);
            if($res['code'] == 200){
                return $res['data'];;
            }

            $this->error = $res['error'];
            return false; 
        } catch (\Exception $e) {
            $this->error = 'curl请求错误';
            return false; 
        }
    }


}
 